#

| Chapter 27 Searching Through Files |

## 27.11 A Multiline Context grep Using sed

[One weakness of the grep family of programs is that they are line-oriented. They read only one line at a time, and so they can't find patterns (such as phrases) that are split across two lines. agrep (27.8) can do multiline searches. One advantage of the cgrep.sed script is that it shows how to handle multiple-line patterns in sed-and can be adapted for work other than searches. -JP ]

cgrep.sed | It may surprise you to learn that a fairly decent context grep program can be built using sed (34.1). This sed version of cgrep is used the same way as the Perl version in article 27.13:

>     $ cgrep -10 system main.c

will find all lines containing the word system in the file main.c, and show 10 additional lines of context above and below each match. (The -`context` option must be at least 1, and defaults to 2 lines.) It differs from the Perl version in that, if several matches occur within the same context, the lines are printed as one large "hunk" rather than repeated smaller hunks. Each new block of context is preceded by the line number of the first occurrence in that hunk. This script can also search for patterns that span lines:

>     cgrep -3 "awk.*perl"

will find all occurrences of the word "awk" where it is followed by the word "perl" somewhere within the next 3 lines. The pattern can be any simple regular expression (26.4), with one notable exception: because you can match across lines, you should use `\n` in place of the `^` and `$` metacharacters.

Article 34.17 explains how the script works.

- GU

27.10 Search RCS Files with rcsgrep |  | 27.12 Make Custom grep Commands (etc.) with perl